package com.george.es.controller.api.article;


import com.george.es.model.entity.Article;
import com.george.es.model.query.ArticleQueryDto;
import com.george.es.result.PageResult;
import com.george.es.result.Result;
import com.george.es.result.StatusCode;
import com.george.es.service.IArticleService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author GeorgeChan
 * @since 2019-06-13
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ArticleController.class);

    private final IArticleService articleService;

    @Autowired
    public ArticleController(IArticleService articleService) {
        this.articleService = articleService;
    }

    /**
     * 保存接口
     * @param article 文章实体
     * @return 返回结果
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result addArticle(@RequestBody Article article) {
        // 其实mybatis-plus可以自动保存，使用方法 articleService.save()
        articleService.addArticle(article);
        return new Result(true, StatusCode.OK, "保存成功！");
    }

    /**
     * 更新接口
     * @param article 文章实体
     * @param id 文章id
     * @return 返回结果
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result updateArticle(@RequestBody Article article, @PathVariable Long id) {
        article.setId(id);
        articleService.updateArticle(article);
        return new Result(true, StatusCode.OK, "更新成功！");
    }

    /**
     * 删除接口
     * @param id 文章id
     * @return 返回结果
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result deleteArticle(@PathVariable Long id) {
        articleService.removeById(id);
        return new Result(true, StatusCode.OK, "删除成功！");
    }

    /**
     * 分页+多条件查询
     * @param queryDto 查询条件封装
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
    public Result findSearch(@RequestBody ArticleQueryDto queryDto , @PathVariable int page, @PathVariable int size){
        PageInfo<Article> articlePageInfo = articleService.findSearch(queryDto, page, size);
        return  new Result(true,StatusCode.OK,"查询成功",  new PageResult<Article>(articlePageInfo.getTotal(), articlePageInfo.getList()));
    }
}

